<?php

class NoBusinessBase_Controller_ConnectionBroker_LongPoll extends Zend_Controller_Action
{

   private $mHost = null;
   private $mPort = null;
   public function init()
   {
      parent::init();

       /* Initialize action controller here */
      $this->_helper->layout->disableLayout();
      $this->_helper->viewRenderer->setNoRender(true); 
   }

   public function connectAction()
   {
      $pRequest = $this->getRequest();
      $this->sendHelper("/connect");
   }

   public function indexAction()
   {
       // action body
   }

   public function messageAction()
   {
      $pRequest = $this->getRequest(); 
      $connectionId = $pRequest->getParam("connectionId");
      $password = $pRequest->getParam("password");
      $postData = $pRequest->getRawBody();
      if($postData === false)
         return;

      $this->sendHelper("/message/connectionId/" . strval($connectionId) . "/password/" . $password, $postData);
   }

   public function updatesAction()
   {
      $pRequest = $this->getRequest();
      $connectionId = $pRequest->getParam("connectionId");
      $password = $pRequest->getParam("password");

      if(!$connectionId || !$password)
         return $this->badStatus();

      if(!$connectionId || !$password)
         return $this->badStatus();

      $this->sendHelper("/updates/connectionId/" . strval($connectionId) . "/password/" . $password); 
   }

   private function badStatus()
   {
      $pStatus = new NoBusinessBase_Utility_Status(NoBusinessBase_Utility_Status::STATUS_BAD, "Request must be get");
      return $this->_helper->json($pStatus());
   }

   private function goodStatus()
   {
      $pStatus = new NoBusinessBase_Utility_Status(NoBusinessBase_Utility_Status::STATUS_OK);
      return $this->_helper->json($pStatus());
   }

   private function sendHelper($uri = "", $postData = null)
   {
      if(!$this->mHost || !$this->mPort)
         return $this->badStatus();

      $addr = "http://" . $this->mHost . ":" . strval($this->mPort) . $uri;
      $client = new Zend_Http_Client($addr);
      if($postData)
      {
         $client->setMethod(Zend_Http_Client::POST);
         $client->setRawData($postData);
      }

      $this->getResponse()->setHeader('Content-Type', 'application/json');
      try
      {
         $response = $client->request();
         $this->getResponse()->appendBody($response->getBody());
      }
      catch(Zend_Http_Client_Exception $e)
      {
         $this->getResponse()->appendBody("");
      }
   }

   protected function setHost($host)
   {
      $this->mHost = $host;
   }

   protected function setPort($port)
   {
      $this->mPort = $port;
   }

}

